package com.mk.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.seckill.exception.GlobalException;
import com.mk.seckill.mapper.OrderMapper;
import com.mk.seckill.pojo.Order;
import com.mk.seckill.pojo.SeckillGoods;
import com.mk.seckill.pojo.SeckillOrder;
import com.mk.seckill.pojo.User;
import com.mk.seckill.service.IGoodsService;
import com.mk.seckill.service.IOrderService;
import com.mk.seckill.service.ISeckillGoodsService;
import com.mk.seckill.service.ISeckillOrderService;
import com.mk.seckill.utils.MD5Util;
import com.mk.seckill.utils.UUIDUtil;
import com.mk.seckill.vo.GoodsVo;
import com.mk.seckill.vo.OrderDetailVo;
import com.mk.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public OrderDetailVo detail(Long orderId) {
        /**
         * @Author hhwu
         * @Description //TODO 根据订单id查询订单详情
         * @Date 14:02 2022/6/9
         * @Param [orderId]
         * @return com.mk.seckill.vo.OrderDetailVo
         **/
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Order order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVo(goodsVo);
//        System.out.println(orderDetailVo);
        return orderDetailVo;
    }

    @Transactional// 事务注解
    @Override
    public Order seckill(User user, GoodsVo goodsVo) {
        /**
         * @Author hhwu
         * @Description //TODO 秒杀处理，修改库存，生成普通订单、生成秒杀订单
         * @Date 15:15 2022/6/8
         * @Param [user, goodsVo]
         * @return com.mk.seckill.pojo.Order
         **/
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 秒杀商品表减库存
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVo.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
//        seckillGoodsService.updateById(seckillGoods);// 优化前的减少库存操作
        // update加了行级排他锁，是原子操作，可以保存线程安全
        boolean result = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()// 当秒杀库存大于0时才更新数据
                .setSql("stock_count = " + "stock_count-1")
                .eq("id", seckillGoods.getId())
                .gt("stock_count", 0));
        if (seckillGoods.getStockCount() < 1) {// 如果秒杀商品的存量更新失败
            // 库存为空时，向redis中设置"isStockEmpty"键。这不同于下单前的判断库存量，这里的库存量是在执行异步下单的过程中判断的。
            valueOperations.set("isStockEmpty", "0");
            return null;
        }
        // 如果秒杀商品的存量更新成功
        // 生成普通订单
        Order order = new Order();//生成订单
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        // 生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goodsVo.getId());
        seckillOrderService.save(seckillOrder);

        // 将秒杀的订单信息在redis中再存一份，以便同一个人多次秒杀同一件商品时，快速返回结果
        valueOperations.set("order:" + user.getId() + ":" + goodsVo.getId(), seckillOrder);
        return order;
    }

    @Override
    public String createPath(User user, Long goodsId) {
        /**
         * @Author hhwu
         * @Description //TODO 生成秒杀地址
         * @Date 17:07 2022/6/13
         * @Param [user, goodsId]
         * @return java.lang.String
         **/
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        // 存储唯一随机接口地址，并设置失效时间
        redisTemplate.opsForValue().set("seckillPath:" + user.getId() + ":" + goodsId, str, 60, TimeUnit.SECONDS);
        return str;
    }

    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        /**
         * @Author hhwu
         * @Description //TODO 校验当前用户是否和当前访问的秒杀地址匹配
         * @Date 17:20 2022/6/13
         * @Param [user, goodsId, path]
         * @return boolean
         **/
        if (user == null || goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillPath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        /**
         * @Author hhwu
         * @Description //TODO 校验验证码
         * @Date 19:29 2022/6/13
         * @Param [user, goodsId, captcha]
         * @return boolean
         **/
        if (user == null || goodsId < 0 || StringUtils.isEmpty(captcha)) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }
}
